import React, { Component } from 'react';
import { Button, Icon } from 'antd';
import * as XLSX from 'xlsx';
import styles from "./css/ExcelComponent.module.css";

class ReadFile extends Component {
    // 转换表格成json
    onImportExcel = file => {
        // 获取上传的文件对象
        const { files } = file.target;
        console.log(files);
        // 通过FileReader对象读取文件
        const fileReader = new FileReader();
        // 文件加载完成时执行;
        fileReader.onload = event => {
            console.log('event', event);
            const { result } = event.target;
            console.log('解析结果', result);
            // 以二进制流方式读取得到整份excel表格对象
            const workbook = XLSX.read(result, { type: 'binary' });
            // 存储获取到的数据
            console.log('workbook', workbook);
            let data = XLSX.utils.sheet_to_json(workbook.Sheets['Sheet1']);
            console.log('data', data);
            
        };
        // 以二进制方式打开文件
        if (files.length > 0) {
            fileReader.readAsBinaryString(files[0]);
        }
    }

    // 打开页面
    inputFocus = () => {
        this.refs.inputFile.click();
    }

    render() {
        return (
            <div>
                <p>只读文件</p>
                <input className={styles.inputFile} type='file' ref="inputFile" onChange={this.onImportExcel} />
                <Button onClick={() => this.inputFocus()}>
                    <Icon type="folder-open" />
                    <span>选择</span>
                </Button>
            </div>
        );
    }
}
export default ReadFile;
